package com.jinlia.show.modules.base.system.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.common.core.exception.MyRuntimeException;
import com.jinlia.show.modules.base.system.entity.Order;
import com.jinlia.show.modules.base.system.entity.OrderItem;
import com.jinlia.show.modules.base.system.mapper.OrderItemMapper;
import com.jinlia.show.modules.base.model.po.GoodsPO;
import com.jinlia.show.modules.base.model.po.OrderItemPO;
import com.jinlia.show.modules.base.wxapp.entity.ShoppingCart;
import com.jinlia.show.modules.base.wxapp.service.ShoppingCartMapperService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderItemMapperService extends ServiceImpl<OrderItemMapper, OrderItem> {

    final ShoppingCartMapperService shoppingCartMapperService;
    final GoodsMapperService goodsMapperService;


    public Map<Long, List<OrderItemPO>> getListVOByOrderId(Long... orderIds) {
        List<OrderItemPO> listVOByOrderId = this.baseMapper.getListVOByOrderId(orderIds);
        Map<Long, List<OrderItemPO>> collect = listVOByOrderId.stream().collect(Collectors.groupingBy(OrderItemPO::getOrderId));
        return collect;
    }

    /**
     * 构造订单项
     *
     * @param order
     */
    public ArrayList<OrderItemPO> createOrderItemByCarIds(List<ShoppingCart> list, Order order) {
        if (CollectionUtils.isEmpty(list)) {
            throw new MyRuntimeException("请传入商品,或数据已更新!!!");
        }
        Map<Long, GoodsPO> mapGoodsVO = goodsMapperService.getMapGoodsVO(list.stream().map(ShoppingCart::getGoodsId).collect(Collectors.toList()));
        ArrayList<OrderItemPO> orderItems = new ArrayList<>();
        BigDecimal orderReceivableMoney = order.getReceivableMoney().subtract(order.getDeliveryMoney());//订单应收金额(包含服务费) 打折后 -运费
        //订单实际折扣
        BigDecimal originalMoney = order.getOriginalMoney().subtract(order.getDeliveryMoney());//订单原价 - 运费
        BigDecimal orderDiscountRate = orderReceivableMoney.divide(originalMoney, 2, RoundingMode.HALF_UP); //订单总折扣
        BigDecimal skuReceivableSum = BigDecimal.ZERO;
        for (int i = 0; i < list.size(); i++) {
            ShoppingCart shoppingCart = list.get(i);
            OrderItemPO orderItemVO = new OrderItemPO();
            orderItems.add(orderItemVO);
            orderItemVO.setOrderId(order.getId());//订单id
            orderItemVO.setGoodsId(shoppingCart.getGoodsId());//商品id
            orderItemVO.setGoodsNum(shoppingCart.getNum());//数量
            orderItemVO.setUnitPrice(shoppingCart.getUnitPrice());//基础价
//            orderItemVO.setOr(mapGoodsVO.get(shoppingCart.getGoodsId()).getGoodsPics());
            orderItemVO.setGoodsName(mapGoodsVO.get(shoppingCart.getGoodsId()).getGoodsName());//商品名
            orderItemVO.setSkuName(shoppingCart.getSkuName());
            orderItemVO.setGoodsType(mapGoodsVO.get(shoppingCart.getGoodsId()).getGoodsType());//商品类型
            //计算单项折扣
            if (i == (list.size() - 1)) { //最后一项用减法
                BigDecimal subtract = orderReceivableMoney.subtract(skuReceivableSum);
                orderItemVO.setReceivableMoney(subtract);//设置单项应收
                skuReceivableSum = skuReceivableSum.add(subtract);//设单项已收合计==>
            } else {
                // skuPrice * 数量 * 折扣率 = 原价

            }
            //被折扣的金额
            this.save(orderItemVO);//保存并回显赋值到ItemSku
        }
        return orderItems;
    }

    public List<OrderItem> initOrderItems(Order newOrder, List<OrderItem> items) {
        //计算订单折扣
        BigDecimal orderDiscountRate = newOrder.getReceivableMoney().divide(newOrder.getOriginalMoney(), 2, RoundingMode.HALF_UP);
        //计算订单详情的应收金额
        BigDecimal skuReceivableSum = BigDecimal.ZERO;
        for (OrderItem item : items) {
            item.setOrderId(newOrder.getId());
            item.setReceivableMoney(item.getUnitPrice().multiply(new BigDecimal(item.getGoodsNum())).multiply(orderDiscountRate).setScale(2, RoundingMode.HALF_UP));
            skuReceivableSum = skuReceivableSum.add(item.getReceivableMoney());
        }
        //订单详情应收金额和订单应收金额不一致==> 修正
        if (skuReceivableSum.compareTo(newOrder.getReceivableMoney()) != 0) {
            OrderItem orderItem = items.get(0);
            BigDecimal fixedReceivableMoney = orderItem.getReceivableMoney().subtract(skuReceivableSum);
            orderItem.setReceivableMoney(fixedReceivableMoney);
        }
        for (OrderItem item : items){
            if (item.getDiscountMoney() == null) {
                item.setDiscountMoney(item.getOriginalMoney().subtract(item.getReceivableMoney()));
            }
        }
        return items;
    }
}
